package com.nxn.core.service.impl;

import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;

import javax.annotation.PostConstruct;
import javax.annotation.PreDestroy;

import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.nxn.core.dao.EntityDao;
import com.nxn.core.dao.UserDao;
import com.nxn.core.model.Role;
import com.nxn.core.model.RoleAuth;
import com.nxn.core.model.User;
import com.nxn.core.service.RoleAuthService;
import com.nxn.core.service.UserService;

/**
 * Implement Services needed to edit and save
 * a user object's state.
 * @author Michael
 *
 */

@Service
public class UserServiceImpl extends EntityManagerImpl<User, Long> implements UserService {
	
	@Autowired
	private UserDao userDao;
	
    @Autowired
	private RoleAuthService roleAuthService;
	
	@Override
	public EntityDao<User, Long> getSearchImpl() {
		return userDao;
	}
	
	@Override
	public User findUserByLoginName(String username) {
		
		List<User> users = userDao.findByProperty("username", username);
		
		return users.size()>0 ? users.get(0) : null;
	}

	@Override
	public User login(String username, String password) {

		if(StringUtils.isNotEmpty(username.trim()) && StringUtils.isNotEmpty(password)) {
			Map<String, Object> map = new HashMap<String, Object>();
			map.put("username", username);
			map.put("password", password);
			
			List<User> users = userDao.findByNamedQueryAndNameParam("findUserByUsernameAndPassword", map);
			return users.size()>0 ? users.get(0) : null;
		}
		
		return null;
	}

	@Override
	public List<RoleAuth> findMenuResourceByUsername(String username) {
		
		User currentUser = findUserByLoginName(username);
		
		Set<Role> roles = currentUser.getRoles();
		Collection<Long> roleIds = new ArrayList<Long>();
		for(Role role : roles) {
			roleIds.add(role.getId());
		}
		
		return roleAuthService.findMenuResourceByRoles(roleIds);
	}
	
	
	@PostConstruct
	public void init() {

	}

	@PreDestroy
	public void destroy() {

	}

}
